@echo off

:: file check
if not exist OhScrCpy.exe (
    echo OhScrCpy.exe not found
    exit /b 1
)

if not exist scrcpy_server (
    echo scrcpy_server not found
    exit /b 1
)

:: command check
where>nul 2>nul hdc
if not %ERRORLEVEL% == 0 (
    echo hdc command not found
    exit /b 1
)

:: hdc device check
for /f %%i in ('hdc list targets') do (set device_key=%%i)
if "%device_key%" == "[Empty]" (
    echo hdc device not found
    exit /b 1
)

:: kill running server and delete file
hdc -t %device_key% shell "pkill -9 scrcpy_server"
hdc -t %device_key% shell "rm -f /data/tmp/scrcpy_server"

:: send scrcpy server file to target device
hdc -t %device_key% shell "mkdir /data/tmp"
hdc -t %device_key% file send scrcpy_server /data/tmp/scrcpy_server
hdc -t %device_key% shell "chmod +x /data/tmp/scrcpy_server"

:: start scrcpy server and set forward proxy
hdc -t %device_key% shell "./data/tmp/scrcpy_server>/dev/null 2>&1 &"
hdc -t %device_key% fport tcp:8000 tcp:8000

:: wait 1s for server ready then start client
timeout /t 1
OhScrCpy.exe

:: exit, remove forward proxy
hdc -t %device_key% fport rm tcp:8000 tcp:8000